package com.wust.smartcity.admin.server.core.mq.consumer;


import com.alibaba.fastjson.JSONObject;
import com.wust.smartcity.admin.server.core.dao.SysDataSourceMapper;
import com.wust.smartcity.common.entity.sys.datasource.SysDataSource;
import com.wust.smartcity.common.enums.RabbitMqOperationTypeEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author ：wust
 * @date ：Created in 2019/7/19 15:21
 * @description：管理员创建代理商，插入数据源记录
 * @version:
 */
@Component
@RabbitListener(
        containerFactory = "singleListenerContainer",
        bindings = @QueueBinding(
                value = @Queue(
                        value = "${spring.rabbitmq.datasource.queue.name}",
                        durable = "${spring.rabbitmq.datasource.queue.durable}"
                ),
                exchange = @Exchange(
                        value = "${spring.rabbitmq.datasource.exchange.name}",
                        durable = "${spring.rabbitmq.datasource.exchange.durable}",
                        type = "${spring.rabbitmq.datasource.exchange.type}",
                        ignoreDeclarationExceptions = "${spring.rabbitmq.datasource.exchange.ignoreDeclarationExceptions}"
                ),
                key = "${spring.rabbitmq.datasource.routing-key}"
        )
)
public class Consumer4DataSourceQueue {
    static Logger logger = LogManager.getLogger(Consumer4DataSourceQueue.class);
    @Autowired
    private SysDataSourceMapper sysDataSourceMapper;

    @RabbitHandler
    public void process(JSONObject jsonObject) {
        logger.info("初始化数据源消费队列：{}",jsonObject);
        System.out.println("##########数据源=" + jsonObject.toJSONString());
        if (RabbitMqOperationTypeEnum.OPR_ADD.name().equals(jsonObject.getString("opt"))) {
            SysDataSource dataSource = jsonObject.getObject("entity", SysDataSource.class);
            SysDataSource dataSourceSearch = new SysDataSource();
            dataSourceSearch.setName(dataSource.getName());
            if (sysDataSourceMapper.selectOne(dataSourceSearch) == null) {
                sysDataSourceMapper.insert(dataSource);
            }else{
                logger.info("初始化数据源消费队列：已存在");
            }
        }
    }
}
